package com.treeman.controller.user;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.treeman.user.User;
import com.treeman.user.UserRole;
import com.treeman.user.UserValidator;
import com.treeman.user.exception.UserExistsException;
import com.treeman.user.service.UserService;

@Controller
public class UserRegistrationController {

	private static Logger log = Logger
			.getLogger(UserRegistrationController.class);

	@Autowired
	private UserValidator userValidator;

	@Autowired
	private UserService userService;

	@RequestMapping(value = "/register", method = RequestMethod.GET)
	public ModelAndView getRegistrationForm() {

		ModelAndView mav = new ModelAndView("/user/register");
		mav.addObject("user", new User());
		return mav;
	}

	@RequestMapping(value = "/register", method = RequestMethod.POST)
	public ModelAndView registerAccount(User user, BindingResult result) {

		userValidator.validate(user, result);
		if (result.hasErrors())
			return new ModelAndView("/user/register");

		user.addRole(new UserRole(UserRole.Role.ROLE_USER));
		try {
			userService.registerUser(user);
			log.debug("Registration of user: " + user.getUsername()
					+ " completed successfully");
			return new ModelAndView("/user/registration-success");
		} catch (UserExistsException e) {
			log.info("User " + user.getUsername() + " already exists!");
		} catch (DataAccessException e1) {
			log.error("DataAccessException: ", e1);
		} catch (Exception e2) {
			log.error("Nieoczekiwany błąd: ", e2);
		}

		return new ModelAndView("/user/registration-success");
	}
}
